/**
 *
 * ......................我佛慈悲.......................
 *                       _oo0oo_
 *                      o8888888o
 *                      88" . "88
 *                      (| -_- |)
 *                      0\  =  /0
 *                    ___/`---'\___
 *                  .' \\|     |// '.
 *                 / \\|||  :  |||// \
 *                / _||||| -卍-|||||- \
 *               |   | \\\  -  /// |   |
 *               | \_|  ''\---/''  |_/ |
 *               \  .-\__  '-'  ___/-. /
 *             ___'. .'  /--.--\  `. .'___
 *          ."" '<  `.___\_<|>_/___.' >' "".
 *         | | :  `- \`.;`\ _ /`;.`/ - ` : | |
 *         \  \ `_.   \_ __\ /__ _/   .-` /  /
 *     =====`-.____`.___ \_____/___.-`___.-'=====
 *                       `=---='
 *
 *..................佛祖开光 ,永无BUG....................
 *         CSDN博客:http://blog.csdn.net/song5347
 *       github地址:https://github.com/lingsuiderongyan
 *             邮箱:lingsuiderongyan@163.com
 */

import UIKit

//重用标记
private let HomeTableViewCellIdentifier = "HomeTableViewCellIdentifier"

//MARK: - 首页
class LSHomeViewController: LSVisitorTableViewController {
    
    
    //MARK: - 使用懒加载的方式创建所需要的ViewModel
    private lazy var statusListViewModel: LSStatusListViewModel = LSStatusListViewModel()
    
    //MARK: - 风火轮
    private lazy var pullUpView: UIActivityIndicatorView = {
        
        let view = UIActivityIndicatorView(activityIndicatorStyle: UIActivityIndicatorViewStyle.WhiteLarge)
        view.color = UIColor.redColor()
        
        return view
    }()
    
    //MARK: - 系统的下拉刷新控件
    private lazy var refreshCtr: UIRefreshControl = {
        
        let ctr = UIRefreshControl()
        
        ctr.addTarget(self, action: "pullDownRefresh", forControlEvents: .ValueChanged)
        
        return ctr
    }()
    
    //MARK: - 自定义下拉刷新空间
    private lazy var pullDownView: LSRefreshControl = {
        
        let ctr = LSRefreshControl()
        
        ctr.addTarget(self, action: "pullDownRefresh", forControlEvents: .ValueChanged)
        
        return ctr
    }()
    
    //MARK: - tip动画label
    private lazy var tipLabel: UILabel = {
        
        let label = UILabel(fontSize: 12, textColor: UIColor.whiteColor())
        label.backgroundColor = UIColor.orangeColor()
        label.text = "没有加载到微博数据"
        label.textAlignment = .Center
        
        //默认隐藏
        label.hidden = true
        
        return label
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        //MARK: - 判断用户是否登录过
        if isLogin {
            
            setupUI()
            
            //登陆成功
            loadData()
            
        } else {
            //  设置访客视图信息
            visitorView?.updateVisitorViewInfo(nil, imageName: nil)
        }
        
        //MARK: - 初始化导航条
        setupNav()
        
    }
    
    //MARK: - 添加控件\设置约束
    private func setupUI() {
        
        //设置tableView相关操作
        setupTableView()
        
        //判断导航控制器是否存在,存在插入tipLabel
        if let nav = self.navigationController {
            
            tipLabel.frame = CGRect(x: 0, y: CGRectGetMaxY(nav.navigationBar.frame) - 30, width: nav.navigationBar.width, height: 30)
            nav.view.insertSubview(tipLabel, belowSubview: nav.navigationBar)
            
        }
        
    }
    
    //MARK: - 内部控制方法
    //标题按钮
    private func setupNav(){
        //添加导航条按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem(imageName: "navigationbar_friendsearch", target: self, action: Selector("leftBtnClick"))
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(imageName: "navigationbar_pop", target: self, action: Selector("rightBtnClick"))
        
        //MARK: - 添加标题按钮
        let titleButton = LSTitleButton()
        titleButton.setTitle("零碎de容颜", forState: UIControlState.Normal)
        titleButton.addTarget(self, action: Selector("titleBtnClick:"), forControlEvents: UIControlEvents.TouchUpInside)
        navigationItem.titleView = titleButton
    }

    @objc private func titleBtnClick(btn: LSTitleButton){
        btn.selected = !btn.selected
    }
    
    @objc private func leftBtnClick(){
        //print("")
    }
    
    @objc private func rightBtnClick(){
        //print("")
    }
    
    //MARK: - 设置tableView相关操作
    private func setupTableView() {
        //注册cell
        tableView.registerClass(LSStatusTabViewCell.self, forCellReuseIdentifier: HomeTableViewCellIdentifier)
        //设置行高
        tableView.rowHeight = UITableViewAutomaticDimension
        //预估行高
        tableView.estimatedRowHeight = 200
        
        //去掉分隔线
        tableView.separatorStyle = .None
        
        //添加上刷新控件
        tableView.tableFooterView = pullUpView
        
        //指定大小
        pullUpView.sizeToFit()
        
        //添加系统下拉刷新方式1
        //self.refreshControl = refreshCtr
        //添加系统下拉刷新方式2
        //tableView.addSubview(refreshCtr)
        //使用自定义下拉刷新控件
        tableView.addSubview(pullDownView)
        
    }
    
    @objc private func pullDownRefresh() {
        
        loadData()
        
    }
    
    //MARK: - 结束刷新的方法
    private func endRefreshing() {
        
        //停止风火轮
        pullUpView.stopAnimating()
        //结束系统下拉刷新的状态
        refreshCtr.endRefreshing()
        //结束自定义下拉刷新的状态
        pullDownView.endRefreshing()
        
    }
    
    //MARK: - 根据服务器返回的信息显示tip文字
    private func startAnimation(message: String) {
        
        //判断视图,如果正常显示正在执行动画,让其直接返回不执行下面的代码
        if tipLabel.hidden == false {
            return
        }
        
        //设置显示文字
        tipLabel.text = message
        
        //显示tipLabel
        tipLabel.hidden = false
        
        UIView.animateWithDuration(1, animations: { () -> Void in
            self.tipLabel.transform = CGAffineTransformMakeTranslation(0, self.tipLabel.height)
            }) { (_) -> Void in
                UIView.animateWithDuration(1, animations: { () -> Void in
                    self.tipLabel.transform = CGAffineTransformIdentity
                    }, completion: { (_) -> Void in
                        //隐藏tipLabel
                        self.tipLabel.hidden = true
                })
        }
        
    }
    
    //MARK: - 加载微博数据
    private func loadData() {
        
        statusListViewModel.loadData(pullUpView.isAnimating()) { (isSuccess, message) -> () in
            
            //开启tip动画
            if !self.pullUpView.isAnimating() {
                self.startAnimation(message)
            }
            
            
            //不调用的话,风火轮会之一存在而不刷新
            self.endRefreshing()
            
            if isSuccess {
                //数据请求成功重写刷新数据
                self.tableView.reloadData()
            } else {
                print("数据请求异常")
            }
        }
    }
    
}

//MARK: - UITableViewDataSource数据源代理
extension LSHomeViewController {
    
    override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        
        return statusListViewModel.statusList.count
    }
    
    override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCellWithIdentifier(HomeTableViewCellIdentifier, forIndexPath: indexPath) as! LSStatusTabViewCell
        
        //给cell绑定数据
        cell.statusViewModel = statusListViewModel.statusList[indexPath.row]
        
        //取消选中颜色
        cell.selectionStyle = .None
        
        return cell
    }
    
    override func tableView(tableView: UITableView, willDisplayCell cell: UITableViewCell, forRowAtIndexPath indexPath: NSIndexPath) {
        if indexPath.row == statusListViewModel.statusList.count - 1 && !pullUpView.isAnimating() {
            
            print("最后一天的数据")
            
            //开启风火轮
            pullUpView.startAnimating()
            //加载更多数据
            loadData()
        }
    }
}




















